package com.guinea.account.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.guinea.account.entity.Contact;
import com.guinea.account.entity.User;
import com.guinea.account.service.ContactManager;
import com.guinea.account.service.UserManager;
import com.guinea.core.service.CRUDManager;
import com.guinea.core.web.StrutsEntityAction;

public class ContactAction extends StrutsEntityAction {
	public static final String SUCCESS = "userList";
	
	private UserManager userManager;

	private ContactManager contactManager;

	public CRUDManager getEntityManager() {
		return (CRUDManager) getContactManager();
	}

	public ContactManager getContactManager() {
		return contactManager;
	}

	public void setContactManager(ContactManager contactManager) {
		this.contactManager = contactManager;
	}
	
	public UserManager getUserManager() {
		return userManager;
	}
	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	/**
	 * 列出所有对象的Action函数.
	 */
	public ActionForward list(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		return mapping.findForward("userList");
	}
	
	/**
	 * 初始化Entity，用于edit,save,view,erase等操作
	 */
	protected Object initEntity(HttpServletRequest request) {
		id = null;
		Long userId = (Long) request.getAttribute("userId");
		//save
		if(userId == null){
			String userIdString = request.getParameter("userId");
			userId = new Long(userIdString);
		}

		Object object = null;
		if (userId != null) {
			object = getContactManager().getContactByUserId(userId);
			if(object != null) id = ((Contact)object).getId();
		}
		return object;
	}
	
	/**
	 * form与list界面所需的参考对象注入.如categoryList,在子类重载.
	 */
	public void refrenceData(ActionForm form, HttpServletRequest request,Object object) {
		Long userId = (Long)request.getAttribute("userId");
		if(userId != null){
			request.setAttribute("user",getUserManager().get(userId));
		}
	}
	/**
	 * 保存Form表单时的回调函数.为业务对象添加更多属性，在子类重载.
	 */
	public void onInitEntity(ActionForm form, HttpServletRequest request,
			Object object) {
		Contact contact = (Contact)object;
        String userIdString = request.getParameter("userId");
        Long userId = new Long(userIdString);
        contact.setUser((User)userManager.get(userId));
        //去除bindEntity中设置的ID
        contact.setId((Long)id);
	}
}
